package com.thinkgsp.webapp.controller;

import java.io.IOException;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.thinkgsp.jxc.service.DataImportService;
import com.thinkgsp.webapp.util.ExtReturn;

/**
 * 资料导入控制器
 * @author evan
 *
 */
@Controller
@RequestMapping(value="/dataimport")
public class DataImportController {

	@Autowired
	private DataImportService importService;
	
	@RequestMapping(value="/uploadFile.do",method=RequestMethod.POST)
	@ResponseBody
	public Object uploadFile(@RequestParam("file") MultipartFile file) {
		try {
			InputStream stream = file.getInputStream();
			DataImportHandler handler = new DataImportHandler(stream);
			DataImportResult result = handler.processImportData();
			stream.close();
			return new ExtReturn(true, "解析文件完成。", result);
		} catch(IOException e) {
			return new ExtReturn("读取上传文件失败,原因:" + e.getMessage());
		} catch(DataImportException e) {
			return new ExtReturn(e.getMessage());
		}
	}
	
	@RequestMapping(value="/submit.do",method=RequestMethod.POST)
	@ResponseBody
	public Object submit(@RequestBody DataImportResult result) {
		try {
			importService.importData(result.getYear(), result.getPeriod(), 
					result.getProducts(), result.getCustomers());
			return new ExtReturn("资料导入成功，系统已经启用。");
		} catch(Exception e) {
			e.printStackTrace();
			return new ExtReturn(false,e.getMessage());
		}
	}
}
